package pd.struct;

import java.util.LinkedList;
import java.util.Collection;

/**
 * An unordered collection of script trees.
 *
 * @author Joshua Swank
 */
public class ScriptForest
{
    /**
     * The list of trees in the forest where the order doesn't matter. It is an ArrayList as the trees will need to be referenced by their arbitrary indices.
     */
    private final Collection<ScriptTree> treeCollection;

    /**
     * Initializes a new empty script forest.
     */
    public ScriptForest()
    {
        treeCollection = new LinkedList<ScriptTree>();
    }

    /**
     * Initializes a new script forest with a specified collection of trees. The collection is hard copied, so the selected data structure is used.
     *
     * @param trees the internal structure that holds the trees.
     */
    protected ScriptForest( Collection<ScriptTree> trees )
    {
        treeCollection = trees;
    }

    /**
     * Adds a collection of script trees to the forest.
     *
     * @param trees the collection of trees to add.
     */
    public final void add( Collection<ScriptTree> trees )
    {
        if( trees != null )
            for( ScriptTree t : trees )
                add( t );
    }

    /**
     * Adds a new tree to the forest.
     *
     * @param tree the script tree to add.
     */
    public final void add( ScriptTree tree )
    {
        if( tree != null && !treeCollection.contains( tree ))
            treeCollection.add( tree );
    }

    /**
     * Removes a script tree from the forest.
     *
     * @param tree the tree to be removed.
     * @return true if the tree was successfully removed, false otherwise.
     */
    public final boolean remove( ScriptTree tree )
    {
        return treeCollection.remove( tree );
    }

    /**
     * Returns the number of trees in the forest.
     *
     * @return the number of trees in the forest.
     */
    public final int size()
    {
        return treeCollection.size();
    }

    /**
     * Returns a string describing the members of the forest.
     *
     * @return a string describing each tree in the forest.
     */
    public final String toString()
    {
        StringBuilder builder = new StringBuilder();

        for( ScriptTree tree : treeCollection )
        {
            builder.append( tree.toString() );
            builder.append( "\n\n" );
        }

        return builder.toString();
    }

    /**
     * Returns an array of trees in the order they were added. Note that the forest itself is unordered.
     *
     * @return an array containing the trees
     */
    protected final ScriptTree[] getTrees()
    {
        return (ScriptTree[])treeCollection.toArray();
    }
}
